package org.jianfa.learn.oss.controller;

import org.apache.commons.lang3.StringUtils;
import org.jianfa.learn.oss.service.StorageService;
import org.jianfa.learn.oss.vo.HttpResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpRequest;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;

@Controller
@RequestMapping("/oss")
public class OssController {

    @Autowired
    StorageService storageService;

    @PostMapping("/upload")
    @ResponseBody
    public HttpResponse upload(@RequestParam("file") MultipartFile file) {
        HttpResponse httpResponse = storageService.upload(file);
        return httpResponse;
    }

    @GetMapping("/download/**")
    @ResponseBody
    public ResponseEntity<Resource> download(HttpServletRequest httpServletRequest) {
        String requestURI = httpServletRequest.getRequestURI();
        String filename = StringUtils.substringAfter(requestURI, "/oss/download/");
        Resource file = storageService.download(filename);
        return ResponseEntity.ok().header(HttpHeaders.CONTENT_DISPOSITION,
                "attachment; filename=\"" + file.getFilename() + "\"").body(file);
    }

    @DeleteMapping("/delete/**")
    @ResponseBody
    public HttpResponse delete(HttpServletRequest httpServletRequest) {
        String requestURI = httpServletRequest.getRequestURI();
        String filename = StringUtils.substringAfter(requestURI, "/oss/delete/");
        HttpResponse httpResponse = storageService.delete(filename);
        return httpResponse;
    }
}
